/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package acceso.util;

//import acceso.aplicacion.Bulldozer;
import javax.servlet.http.HttpServletRequest;
import wf.dto.login.pppermis;
import wf.dto.login.ppregsesiniDto;
import wf3.core.dao.LoginDAO;
import wf3.kernel.WorkflowFactory;

/**
 *
 * @author john
 */
public class LogueoHelper {

    public static boolean loguear(HttpServletRequest request) {
        boolean res = true;
        String p_usuari = request.getParameter("usu");//usuario del sistema
        String p_passwo = request.getParameter("pwd");//password del sistema
        int p_modowf = 0;//Integer.parseInt(request.getParameter("p_modowf"));//modo del sistem (Sale de la opcion del combo)
        String p_nomnav = request.getHeader("user-Agent");//password del sistema
        String p_ipaddr = request.getRemoteAddr();//password del sistema
        int p_cosyst = Integer.parseInt(request.getSession().getServletContext().getInitParameter("co_system"));//password del sistema

        UserSesion userSesion;
        ppregsesiniDto ppregses;
        pppermis permisos;
        LoginDAO DAO = new LoginDAO();
//        System.out.println("Usando>>" + ((Bulldozer) request.getSession().getAttribute("acceso")).getWorkflow().isMaster_login());
//        if (((Bulldozer) request.getSession().getAttribute("acceso")).getWorkflow().isMaster_login()) {
//            DAO = new LoginDAO();
//        } else {
//            DAO = new LoginDAO(0);
//        }

        try {
//            System.out.println("[p_usuari:" + p_usuari + "][p_passwo:" + p_passwo + "][p_modowf:" + p_modowf + "][p_nomnav:" + p_nomnav + "][p_ipaddr:" + p_ipaddr + "][p_cosyst:" + p_cosyst + "]");
            ppregses = DAO.SESION(p_usuari, p_passwo, p_modowf, p_nomnav, p_ipaddr, p_cosyst);
            if (ppregses != null) {
                permisos = DAO.PERMIS(ppregses.getId_sesion(), Short.parseShort(p_cosyst + ""));

//                userSesion = new UserSesion(ppregses, permisos, new LoginBean());
                userSesion = new UserSesion(ppregses, permisos, "", false);
//                request.getSession().setAttribute("sesion", userSesion);
                request.getSession().setAttribute("US", userSesion);
//                request.getSession().setAttribute("user", new User(ppregses.getId_sesion()));//Para cambiar
//                request.getSession().setAttribute("modo", userSesion.getTi_modofr());//Para ELIMINAR!
            } else {
                res = false;
            }
        } catch (Exception ep) {
            System.out.println("ERROR: " + ep);//<-----X
            res = false;
        } finally {
            DAO.CLOSE_SESSION();
        }
        return res;
    }

    public static boolean loguear(HttpServletRequest request, long id_sesion) {
        boolean res = true;
        UserSesion userSesion;
        ppregsesiniDto ppregses;
        pppermis permisos;

        LoginDAO DAO = new LoginDAO((int) id_sesion);

        try {

//            if (((Bulldozer) request.getSession().getServletContext().getAttribute("acceso")).getWorkflow().isMaster_login()) {
            if (WorkflowFactory.getConfiguration().isMs_login()) {
                //Cargando de mi mismo
                ppregses = DAO.SESION(id_sesion);
            } else {
                //pidiendo carga desde el master_login
//                ppregses = DAO.SESION_OVER_MASTER(((Bulldozer) request.getSession().getServletContext().getAttribute("acceso")).getWorkflow().getMaster_login_url(), id_sesion);
                ppregses = DAO.SESION_OVER_MASTER(WorkflowFactory.getConfiguration().getMs_host(), id_sesion);
//                System.out.println("Objecto devuelto de la sesion_over_master:" + ppregses);
            }

            if (ppregses != null) {
//                if (((Bulldozer) request.getSession().getServletContext().getAttribute("acceso")).getWorkflow().isMaster_login()) {
                if (WorkflowFactory.getConfiguration().isMs_login()) {;
//                    permisos = DAO.PERMIS(0, ppregses.getId_sesion(), Short.parseShort(request.getSession().getServletContext().getInitParameter("co_system").toString()));
                    permisos = DAO.PERMIS(ppregses.getId_sesion(), (short) WorkflowFactory.getConfiguration().getCo_system());
                } else {
//                    permisos = DAO.PERMIS_OVER_MASTER(((Bulldozer) request.getSession().getServletContext().getAttribute("acceso")).getWorkflow().getMaster_login_url(), 0, ppregses.getId_sesion(), Short.parseShort(request.getSession().getServletContext().getInitParameter("co_system").toString()));
//                    permisos = DAO.PERMIS_OVER_MASTER(WorkflowFactory.getConfiguration().getMs_host(), 0, ppregses.getId_sesion(), Short.parseShort(request.getSession().getServletContext().getInitParameter("co_system").toString()));
                    permisos = DAO.PERMIS_OVER_MASTER(WorkflowFactory.getConfiguration().getMs_host(), 0, ppregses.getId_sesion(), (short) WorkflowFactory.getConfiguration().getCo_system());
//                    System.out.println("Object devuelto de l permis_over_master");
                }
                wf3.core.bean.LoginBean lBean = new wf3.core.bean.LoginBean();
                lBean.setUserAgent(request.getHeader("User-Agent"));
//                System.out.println(">>>"+lBean.isMobil());
//                userSesion = new UserSesion(ppregses, permisos, lBean);
                userSesion = new UserSesion(ppregses, permisos, "", false);
//                request.getSession().setAttribute("sesion", userSesion);//${userSession.is_movil}
                request.getSession().setAttribute("US", userSesion);//${userSession.is_movil}
//                request.getSession().setAttribute("userSession", userSesion);//${userSession.is_movil}
//                request.getSession().setAttribute("user", new User(ppregses.getId_sesion()));//Para cambiar
//                request.getSession().setAttribute("modo", userSesion.getTi_modofr());//Para ELIMINAR!
            } else {
                System.out.println("Sesion ha expirado");
                res = false;
            }
        } catch (Exception ep) {
            System.out.println("ERROR-class: " + ep.getClass());//<-----X
            if (ep instanceof org.hibernate.exception.SQLGrammarException) {
                System.out.println("ERROR(A): " + ((org.hibernate.exception.SQLGrammarException) ep).getMessage());//<-----X
                System.out.println("ERROR(B): " + ((org.hibernate.exception.SQLGrammarException) ep).getSQLException());//<-----X
            } else {
                System.out.println("ERROR-X: " + ep);//<-----X
            }
            res = false;
        } finally {
            DAO.CLOSE_SESSION();
        }
        return res;
    }

    public static void actualizarEstado(int id_sesion) {
        LoginDAO DAO = new LoginDAO();
        try {
            DAO.ACTUALIZAR(id_sesion);
        } catch (Exception ep) {
            if (ep instanceof org.hibernate.exception.SQLGrammarException) {
                System.out.println("ERROR: " + ((org.hibernate.exception.SQLGrammarException) ep).getMessage());//<-----X
                System.out.println("ERROR: " + ((org.hibernate.exception.SQLGrammarException) ep).getSQLException());//<-----X
            } else {
                System.out.println("ERROR: " + ep);//<-----X
            }
        } finally {
            DAO.CLOSE_SESSION();
        }
    }
}
